﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Xml;

namespace MobileTest
{
    class Program
    {
        static void Main(string[] args)
        {
            bool fromFile=false;
            string[] positionLines;
            string positionString;
            TcpClient client;
            while (true)
            {
                Console.WriteLine("Trying to connect...");
                while (true)
                {
                    try
                    {
                        client = new TcpClient("127.0.0.1", 2055);
                    }
                    catch (Exception e)
                    {
                        client = null;
                    }
                    if(client!=null && client.Connected)
                        break;
                }
                try
                {
                    Stream s = client.GetStream();
                    StreamReader sr = new StreamReader(s);
                    StreamWriter sw = new StreamWriter(s);
                    sw.AutoFlush = true;
                    positionLines = new String[1];
                    if (args.Length > 0)
                        if (args[0] != "")
                        {
                            Console.WriteLine("Detected auto mode. File: {0}", args[0]);
                            positionLines = System.IO.File.ReadAllLines(args[0]);
                            Console.WriteLine("Readed {0} possible positions", positionLines.Length);
                            fromFile = true;
                        }
                        else
                        {

                        }

                    while (true)
                    {
                        positionString = "";
                        bool caughtException = false;
                        if (fromFile)
                        {
                            foreach (string line in positionLines)
                            {
                                string[] position = line.Split(' ');
                                double lat;
                                Double.TryParse(position[0], out lat);
                                double lon;
                                Double.TryParse(position[1], out lon);
                                Console.WriteLine("Sending position: {0} {1}", lat, lon);
                                try
                                {
                                    sw.WriteLine(generatePositionXML(lat, lon));
                                }
                                catch
                                {
                                    caughtException = true;
                                    break;
                                }
                                System.Threading.Thread.Sleep(1000);
                            }

                        }
                        else
                        {
                            positionString = Console.ReadLine();
                            if (positionString == "") break;
                            string[] position = positionString.Split(' ');
                            double lat;
                            Double.TryParse(position[0], out lat);
                            double lon;
                            Double.TryParse(position[1], out lon);
                            sw.WriteLine(generatePositionXML(lat, lon));
                            Console.WriteLine(sr.ReadLine());
                        }
                        if(caughtException)
                            break;
                    }

                    s.Close();
                }
                finally
                {
                    // code in finally block is guranteed 
                    // to execute irrespective of 
                    // whether any exception occurs or does 
                    // not occur in the try block
                    client.Close();
                }
            }
        }

        public static string generatePositionXML(double lat, double lon)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlElement rootNode = xmlDocument.CreateElement("MobilePositionReport");
            xmlDocument.AppendChild(rootNode);

            XmlElement deviceId = xmlDocument.CreateElement("DeviceID");
            deviceId.InnerText = "TESTID";
            rootNode.AppendChild(deviceId);

            XmlElement latitude = xmlDocument.CreateElement("Latitude");
            latitude.InnerText = lat.ToString();
            rootNode.AppendChild(latitude);

            XmlElement longtitude = xmlDocument.CreateElement("Longtitude");
            longtitude.InnerText = lon.ToString();
            rootNode.AppendChild(longtitude);

            return xmlDocument.OuterXml;

            /*using (var stringWriter = new StringWriter())
            using (var xmlTextWriter = XmlWriter.Create(stringWriter))
            {
                xmlDocument.WriteTo(xmlTextWriter);
                xmlTextWriter.Flush();
                return stringWriter.GetStringBuilder().ToString();
            }*/
        }
    }
}
